package com.atguigu.lease.web.app.service.impl;

import com.atguigu.lease.model.entity.BrowsingHistory;
import com.atguigu.lease.web.app.mapper.BrowsingHistoryMapper;
import com.atguigu.lease.web.app.service.BrowsingHistoryService;
import com.atguigu.lease.web.app.vo.history.HistoryItemVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author liubo
 * @description 针对表【browsing_history(浏览历史)】的数据库操作Service实现
 * @createDate 2023-07-26 11:12:39
 */
@Service
@Slf4j
public class BrowsingHistoryServiceImpl extends ServiceImpl<BrowsingHistoryMapper, BrowsingHistory>
        implements BrowsingHistoryService {
    @Autowired
    private BrowsingHistoryMapper browsingHistoryMapper;


    @Override
    public IPage<HistoryItemVo> pageInfo(Page<HistoryItemVo> voPage, Integer userId) {
        return browsingHistoryMapper.IPage(voPage, userId);
    }

    /**
     * 保存浏览历史的接口
     * 异步完成的
     *
     * @param userId
     * @param roomId
     */
    @Override
    public void saveHistory(Integer userId, Long roomId) {
        //实例化对象并赋值
        BrowsingHistory browsingHistory = new BrowsingHistory();
        browsingHistory.setRoomId(roomId);
        browsingHistory.setUserId(userId.longValue());
        browsingHistory.setBrowseTime(new Date());
        //查询库内是否有旧数据
        LambdaQueryWrapper<BrowsingHistory> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BrowsingHistory::getRoomId, roomId);
        queryWrapper.eq(BrowsingHistory::getUserId, userId);
        Long count = browsingHistoryMapper.selectCount(queryWrapper);
        if (count > 0) {
            //有数据
            LambdaUpdateWrapper<BrowsingHistory> updateWrapper =
                    new LambdaUpdateWrapper<BrowsingHistory>()
                            .eq(BrowsingHistory::getRoomId, roomId)
                            .eq(BrowsingHistory::getUserId, userId);
            //覆盖旧数据
            browsingHistoryMapper.update(browsingHistory, updateWrapper);
        } else {
            this.save(browsingHistory);
        }


    }
}




